package com.flyco.modules.oms.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.SecurityUtils;
import com.flyco.poi.excel.ExcelImportUtil;
import com.flyco.poi.excel.def.NormalExcelConstants;
import com.flyco.poi.excel.entity.ExportParams;
import com.flyco.poi.excel.entity.ImportParams;
import com.flyco.poi.excel.view.EntityExcelView;
import com.flyco.common.system.vo.LoginUser;
import com.flyco.common.api.vo.Result;
import com.flyco.common.system.query.QueryGenerator;
import com.flyco.common.util.oConvertUtils;
import com.flyco.modules.oms.entity.OmsOrderBlackArea;
import com.flyco.modules.oms.entity.OmsOrderBlack;
import com.flyco.modules.oms.vo.OmsOrderBlackPage;
import com.flyco.modules.oms.service.IOmsOrderBlackService;
import com.flyco.modules.oms.service.IOmsOrderBlackAreaService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.flyco.common.aspect.annotation.AutoLog;

 /**
 * @Description: 禁止下单表
 * @Author: flyco
 * @Date:   2021-01-14
 * @Version: V1.0
 */
@Api(tags="禁止下单表")
@RestController
@RequestMapping("/f/oms/omsOrderBlack")
@Slf4j
public class OmsOrderBlackController {
	@Autowired
	private IOmsOrderBlackService omsOrderBlackService;
	@Autowired
	private IOmsOrderBlackAreaService omsOrderBlackAreaService;
	
	/**
	 * 分页列表查询
	 *
	 * @param omsOrderBlack
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "禁止下单表-分页列表查询")
    @ApiOperation(value="禁止下单表-分页列表查询", notes="禁止下单表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(OmsOrderBlack omsOrderBlack,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<OmsOrderBlack> queryWrapper = QueryGenerator.initQueryWrapper(omsOrderBlack, req.getParameterMap());
		Page<OmsOrderBlack> page = new Page<OmsOrderBlack>(pageNo, pageSize);
		IPage<OmsOrderBlack> pageList = omsOrderBlackService.page(page, queryWrapper);
		return Result.ok(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param omsOrderBlackPage
	 * @return
	 */
	@AutoLog(value = "禁止下单表-添加")
	@ApiOperation(value="禁止下单表-添加", notes="禁止下单表-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody OmsOrderBlackPage omsOrderBlackPage) {
       OmsOrderBlack omsOrderBlack = new OmsOrderBlack();
		BeanUtils.copyProperties(omsOrderBlackPage, omsOrderBlack);
		omsOrderBlack.setCancelFlag(0);
		omsOrderBlackService.save(omsOrderBlack);
		return Result.ok("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param omsOrderBlackPage
	 * @return
	 */
	@AutoLog(value = "禁止下单表-编辑")
	@ApiOperation(value="禁止下单表-编辑", notes="禁止下单表-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody OmsOrderBlackPage omsOrderBlackPage) {
		OmsOrderBlack omsOrderBlack = new OmsOrderBlack();
		BeanUtils.copyProperties(omsOrderBlackPage, omsOrderBlack);
		omsOrderBlackService.updateById(omsOrderBlack);
		return Result.ok("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "禁止下单表-通过id删除")
	@ApiOperation(value="禁止下单表-通过id删除", notes="禁止下单表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) Long id) {
		omsOrderBlackService.delMain(id);
		return Result.ok("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "禁止下单表-批量删除")
	@ApiOperation(value="禁止下单表-批量删除", notes="禁止下单表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
	    this.omsOrderBlackService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "禁止下单表-通过id查询")
	@ApiOperation(value="禁止下单表-通过id查询", notes="禁止下单表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) Long id) {
		OmsOrderBlack omsOrderBlack = omsOrderBlackService.getById(id);
		return Result.ok(omsOrderBlack);
	}
	
	//===========================以下是子表信息操作相关API====================================
	
	/**
	 * 通过主表id查询禁止下单区域表
	 *
  	 * @param omsOrderBlackArea
	 * @return
	 */
	@AutoLog(value = "禁止下单区域表-通过主表id查询")
    @ApiOperation(value="禁止下单区域表-通过主表id查询", notes="禁止下单区域表-通过主表id查询")
	@GetMapping(value = "/listOmsOrderBlackAreaByMainId")
	public Result<?> listOmsOrderBlackAreaByMainId(OmsOrderBlackArea omsOrderBlackArea,
                								  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                								  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                								  HttpServletRequest req) {
        if(omsOrderBlackArea.getBlackId()!=null) {
            QueryWrapper<OmsOrderBlackArea> queryWrapper = QueryGenerator.initQueryWrapper(omsOrderBlackArea, req.getParameterMap());
            Page<OmsOrderBlackArea> page = new Page<OmsOrderBlackArea>(pageNo, pageSize);
            IPage<OmsOrderBlackArea> pageList =  omsOrderBlackAreaService.page(page, queryWrapper);
            return Result.ok(pageList);
        }else{
            return Result.error("请选择一条记录");
        }
    }
	
	/**
     * 添加禁止下单区域表
     *
     * @param omsOrderBlackArea
     * @return
     */
    @AutoLog(value = "禁止下单区域表-添加")
    @ApiOperation(value="禁止下单区域表-添加", notes="禁止下单区域表-添加")
    @PostMapping(value = "/addOmsOrderBlackArea")
    public Result<?> addOmsOrderBlackArea(@RequestBody OmsOrderBlackArea omsOrderBlackArea) {
        omsOrderBlackAreaService.save(omsOrderBlackArea);
        return Result.ok("添加禁止下单区域表成功！");
    }
    
    /**
     * 编辑禁止下单区域表
     *
     * @param omsOrderBlackArea
     * @return
     */
    @AutoLog(value = "禁止下单区域表-编辑")
    @ApiOperation(value="禁止下单区域表-编辑", notes="禁止下单区域表-编辑")
    @PutMapping("/editOmsOrderBlackArea")
    public Result<?> editOmsOrderBlackArea(@RequestBody OmsOrderBlackArea omsOrderBlackArea) {
        omsOrderBlackAreaService.updateById(omsOrderBlackArea);
        return Result.ok("编辑禁止下单区域表成功！");
    }
    
    /**
     * 通过id删除禁止下单区域表
     *
     * @param id
     * @return
     */
    @AutoLog(value = "禁止下单区域表-通过id删除")
    @ApiOperation(value="禁止下单区域表-通过id删除", notes="禁止下单区域表-通过id删除")
    @DeleteMapping(value = "/deleteOmsOrderBlackArea")
    public Result<?> deleteOmsOrderBlackArea(@RequestParam(name = "id", required = true) String id) {
       omsOrderBlackAreaService.removeById(id);
        return Result.ok("删除禁止下单区域表成功！");
    }
	
	/**
     * 批量删除禁止下单区域表
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "禁止下单区域表-批量删除")
    @ApiOperation(value="禁止下单区域表-批量删除", notes="禁止下单区域表-批量删除")
    @DeleteMapping(value = "/deleteBatchOmsOrderBlackArea")
    public Result<?> deleteBatchOmsOrderBlackArea(@RequestParam(name = "ids", required = true) String ids) {
        if (ids == null || "".equals(ids.trim())) {
            return Result.error("参数不识别！");
        } 
        this.omsOrderBlackAreaService.removeByIds(Arrays.asList(ids.split(",")));
       	return Result.ok("批量删除成功！");

    }
    

    /**
    * 导出excel
    *
    * @param request
    * @param omsOrderBlack
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, OmsOrderBlack omsOrderBlack) {
      // Step.1 组装查询条件
      QueryWrapper<OmsOrderBlack> queryWrapper = QueryGenerator.initQueryWrapper(omsOrderBlack, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //Step.2 获取导出数据
      List<OmsOrderBlackPage> pageList = new ArrayList<OmsOrderBlackPage>();
      List<OmsOrderBlack> omsOrderBlackList = omsOrderBlackService.list(queryWrapper);
      for (OmsOrderBlack temp : omsOrderBlackList) {
          OmsOrderBlackPage vo = new OmsOrderBlackPage();
          BeanUtils.copyProperties(temp, vo);
          List<OmsOrderBlackArea> omsOrderBlackAreaList = omsOrderBlackAreaService.selectByMainId(temp.getId());
          vo.setOmsOrderBlackAreaList(omsOrderBlackAreaList);
          pageList.add(vo);
      }
      //Step.3 调用AutoPoi导出Excel
      ModelAndView mv = new ModelAndView(new EntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "禁止下单表");
      mv.addObject(NormalExcelConstants.CLASS, OmsOrderBlackPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("禁止下单表数据", "导出人:"+sysUser.getRealname(), "禁止下单表"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<OmsOrderBlackPage> list = ExcelImportUtil.importExcel(file.getInputStream(), OmsOrderBlackPage.class, params);
              for (OmsOrderBlackPage page : list) {
                  OmsOrderBlack po = new OmsOrderBlack();
                  BeanUtils.copyProperties(page, po);
                  omsOrderBlackService.saveMain(po, page.getOmsOrderBlackAreaList());
              }
              return Result.ok("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.ok("文件导入失败！");
    }
}
